package com.sjzl.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.opensymphony.xwork2.ActionContext;
import com.sjzl.dto.UserDto;
import com.sjzl.entity.Friend;
import com.sjzl.entity.User;
import com.sjzl.service.UserService;
import com.sjzl.util.MD5Encrypt;

@Component("userServiceImpl")
public class UserServiceImpl extends ServiceImpl<User> implements UserService{

	@Override
	public void create(User entity) {
		// TODO Auto-generated method stub
		
	}
	
	public void checkLogin(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession httpSession = request.getSession();
		String cookieAccount = null;
		if (request.getCookies() != null) {
			for (Cookie cookie : request.getCookies()) {
				if (cookie.getName().equals("account"))
					cookieAccount = cookie.getValue();
			}
		}
		if(cookieAccount != null && cookieAccount != ""){
			if(httpSession.getAttribute("sessionUser") == null){
				System.out.println("目前浏览器Session中没有用户的信息！");
				ActionContext actionContext=ActionContext.getContext();
				actionContext.getSession().put("sessionUser", this.getUserByAccount(cookieAccount));
			}
		}
		
	}

	public boolean login(UserDto userDto, Integer timeout,
			HttpServletRequest request, HttpServletResponse response){
		String account = userDto.getAccount();
		String password = userDto.getPassword();

		User user = this.getUser(account, password);

		if (user != null) {
			// 把帐号连同密钥使用MD5后加密后保存
			String ssid = MD5Encrypt.calcMD5(account + MD5Encrypt.getKey());
			// 把帐号保存到Cookie中 并控制有效期
			Cookie accountCookie = new Cookie("account", account);
			accountCookie.setMaxAge(timeout);

			// 把加密结果保存到Cookie中 并控制有效期
			Cookie ssidCookie = new Cookie("ssid", ssid);
			ssidCookie.setMaxAge(timeout);

			response.addCookie(accountCookie);
			response.addCookie(ssidCookie);
			
			ActionContext actionContext=ActionContext.getContext();
			actionContext.getSession().put("sessionUser", this.getUserByAccount(account));
			
			return true;
		}

		return false;
	}

	@Transactional
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		String cookieAccount = null;
		if (request.getCookies() != null) {
			for (Cookie cookie : request.getCookies()) {
				if (cookie.getName().equals("account"))
					cookieAccount = cookie.getValue();
			}
		}

		this.saveDateLastActived(cookieAccount);

		// 删除Cookie中的帐号
		Cookie accountCookie = new Cookie("account", null);
		accountCookie.setMaxAge(0);

		// 删除Cookie中的加密结果
		Cookie ssidCookie = new Cookie("ssid", null);
		ssidCookie.setMaxAge(0);

		response.addCookie(accountCookie);
		response.addCookie(ssidCookie);
		
		//设置用户回话为空
		ActionContext actionContext=ActionContext.getContext();
		actionContext.getSession().put("sessionUser", null);
		
		//重置消息状态
		actionContext.getSession().put("newMessage", false);
	}

	public User getUser(String account, String password) {
		Object[] params = { account, password };
		List<User> userList = this.getDao().list(
				"from User u where u.account = ? and u.password = ?", params);
		if (userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	public User getUserByAccount(String account) {
		List<User> userList = this.getDao().list(
				"from User u where u.account = ? ", account);
		if (userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	@Transactional
	public void saveDateLastActived(String account) {
		User user = this.getUserByAccount(account);
		user.setDateLastActived(new Date());
		this.getDao().update(user);
	}

	@Transactional
	public void saveDateLastActived(User user) {
		int id = user.getId();
		User u = this.getDao().get(User.class, id);
		u.setDateLastActived(new Date());
		this.getDao().update(u);
	}
	
	@Transactional
	public boolean updateIntegral(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession httpSession = request.getSession();
		User sessionUser = (User) httpSession.getAttribute("sessionUser");
		User dbUser = this.getDao().get(User.class, sessionUser.getId());
		Integer integral = dbUser.getIntegral();
		if(integral<=0){
			return false;
		}
		dbUser.setIntegral(integral-5);
		this.getDao().update(dbUser);
		return true;
	}
	
	@Transactional
	public void updateUserInfo(User user, File upload, String uploadFileName,
			String uploadContentType) {
		String realpath = ServletActionContext.getServletContext().getRealPath("/userUploadFile");//获取真实路径
		String realName = UUID.randomUUID().toString()+ uploadFileName.substring(uploadFileName.lastIndexOf("."));// 保存的文件名称，使用UUID+后缀进行保存，可以确保重复上传
		File file = new File(realpath);
		if(!file.exists()) file.mkdirs();	//如果不存在就创建
		try {
			FileUtils.copyFile(upload, new File(file, realName));//上传文件到服务器
		} catch (IOException e) {
			e.printStackTrace();
		}
		user.setHeadImageSrc(realName);
		user.setPosts(null);
		user.setBoards(null);
		update(user);
	}
	
}
